package demoMod.plugins.mod.sts.module;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import demoMod.plugins.mod.sts.module.vo.ProjectConfigVO;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

public class ProjectGenerator extends FreemarkerConfiguration {

    public void doGenerator(Project project, String entryPath, ProjectConfigVO projectConfig) {
        //创建工程主POM文件
        generateProjectPOM(project, entryPath, projectConfig);
        //创建工程资源目录结构
        generateProjectResources(project, entryPath, projectConfig);
        //创建Mod主类
        generateModEntry(project, entryPath, projectConfig);
        //生成ModTheSpire.json
        generateModInfo(project, entryPath, projectConfig);
        //生成其他信息
        generateCommon(project, entryPath, projectConfig);
    }

    private void generateProjectPOM(Project project, String entryPath, ProjectConfigVO projectConfig) {
        writeFile(project, "/", entryPath, "pom.xml", "pom.ftl", projectConfig);
    }


    private void generateProjectResources(Project project, String entryPath, ProjectConfigVO projectConfig) {

    }


    private void generateModEntry(Project project, String entryPath, ProjectConfigVO projectConfig) {

    }


    private void generateModInfo(Project project, String entryPath, ProjectConfigVO projectConfig) {

    }


    private void generateCommon(Project project, String entryPath, ProjectConfigVO projectConfig) {

    }

    public void writeFile(Project project, String packageName, String entryPath, String name, String ftl, Object dataModel) {
        VirtualFile virtualFile;
        try {
            virtualFile = createPackageDir(packageName, entryPath).createChildData(project, name);
            StringWriter stringWriter = new StringWriter();
            Template template = super.getTemplate(ftl);
            template.process(dataModel, stringWriter);
            virtualFile.setBinaryContent(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }

    private static VirtualFile createPackageDir(String packageName, String entryPath) {
        String path = FileUtil.toSystemIndependentName(entryPath + "/" + StringUtil.replace(packageName, ".", "/"));
        new File(path).mkdirs();
        return LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
    }
}
